package com.thirteenClassicsServer.controller;

import com.thirteenClassics.dto.*;
import com.thirteenClassics.entity.CatalogBook;
import com.thirteenClassics.entity.Entry;
import com.thirteenClassics.entity.Picture;
import com.thirteenClassics.enumeration.ActionEnum;
import com.thirteenClassics.exception.BaseException;
import com.thirteenClassics.result.PageResult;
import com.thirteenClassics.result.Result;
import com.thirteenClassics.vo.EntryCatalogQueryVO;
import com.thirteenClassics.vo.PictureVO;
import com.thirteenClassics.vo.SentenceVO;
import com.thirteenClassicsServer.common.CommonService;
import com.thirteenClassicsServer.mapper.CatalogBookMapper;
import com.thirteenClassicsServer.mapper.PictureMapper;
import com.thirteenClassicsServer.mapper.SentenceMapper;
import com.thirteenClassicsServer.service.IBookService;
import com.thirteenClassicsServer.service.IEntryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.thirteenClassicsServer.service.impl.XmlParseService.toGetTableName;

@Slf4j
@RestController
@RequestMapping("/entry")
public class EntryController {
    @Resource
    private IBookService bookService;
    @Resource
    private IEntryService entryService;
    @Autowired
    private SentenceMapper sentenceMapper;
    @Autowired
    private CatalogBookMapper catalogBookMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private PictureMapper pictureMapper;


    @GetMapping()
    public Result<PageResult> selectEntryBook(EntryPageQueryDTO entryPageQueryDTO) {
        log.info("书目录入分页查询：{}", entryPageQueryDTO);
        PageResult pageResult = entryService.pageQuery2(entryPageQueryDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/catalogAndAll")
    public Result<EntryCatalogQueryVO> selectCatalogAndAll(EntryCatalogQueryDTO entryCatalogQueryDTO) {
        log.info("查询当前页的内容：{}", entryCatalogQueryDTO);
        EntryCatalogQueryVO entryCatalogQueryVO = entryService.selectCatalogAndAll(entryCatalogQueryDTO);
        entryService.saveOperationHistory(entryCatalogQueryDTO, ActionEnum.ENTRYACTION.getCode());
//        log.info("查询当前页的内容：{}", entryCatalogQueryVO);
        log.info("当前页的内容查询结果：id={},name={},ancestors={},catalogId={},entryId={},alias={},bookLang={},jdbLink={},jdb={},tot={},contents1={},contents2={},contentDzs={},dybSentence={},sentence={},sentence2={},dzSentence={},manwengLd={},bookOptime={},notes={},bookOperator={}",
                entryCatalogQueryVO.getId(), entryCatalogQueryVO.getName(), entryCatalogQueryVO.getAncestors(),
                entryCatalogQueryVO.getCatalogId(), entryCatalogQueryVO.getEntryId(), entryCatalogQueryVO.getAlias(),
                entryCatalogQueryVO.getBookLang(), entryCatalogQueryVO.getJdbLink(), entryCatalogQueryVO.getJdb(),
                entryCatalogQueryVO.getTot(), entryCatalogQueryVO.getContents1(), entryCatalogQueryVO.getContents2(),
                entryCatalogQueryVO.getContentDzs(), entryCatalogQueryVO.getDybSentence(), entryCatalogQueryVO.getSentence(),
                entryCatalogQueryVO.getSentence2(), entryCatalogQueryVO.getDzSentence(), entryCatalogQueryVO.getManwengLd(),
                entryCatalogQueryVO.getBookOptime(), entryCatalogQueryVO.getNotes(), entryCatalogQueryVO.getBookOperator());
        return Result.success(entryCatalogQueryVO);
    }

    @GetMapping("/catalogAndAllNew")
    public Result<EntryCatalogQueryVO> selectCatalogAndAllNew(EntryCatalogQueryDTO entryCatalogQueryDTO) {
        log.info("查询当前页的内容无图片和经典版句子：{}", entryCatalogQueryDTO);
        EntryCatalogQueryVO entryCatalogQueryVO = entryService.selectCatalogAndAllNew(entryCatalogQueryDTO);
        entryService.saveOperationHistory(entryCatalogQueryDTO, ActionEnum.ENTRYACTION.getCode());
        log.info("查询当前页的内容无图片和经典版句子：{}", entryCatalogQueryVO);
        return Result.success(entryCatalogQueryVO);
    }

    @GetMapping("/jdbContentForChapter")
    public Result<List<SentenceVO>> jdbContentForChapter(JdbContentForChapterDTO jdbContentForChapterDTO) {
        log.info("分页查询当前章节的所有经典版句子：{}", jdbContentForChapterDTO);
        return Result.success(entryService.jdbContentForChapter(jdbContentForChapterDTO));
    }

    @PostMapping("/sentenceTotal")
    public Result<Integer> querySentenceTotal (@RequestBody QuerySentenceTotalDTO querySentenceTotalDTO){
        log.info("查询当前章节的所有句子数：{}", querySentenceTotalDTO);
        CatalogQueryDTO catalogQueryDTO = new CatalogQueryDTO();
        BeanUtils.copyProperties(querySentenceTotalDTO, catalogQueryDTO);
        CatalogBook catalogBook = commonService.getMinorityCatalogBookByBookAndIndex(catalogQueryDTO);
        return Result.success(sentenceMapper.selectAllSentenceSum(catalogBook.getId(),
                toGetTableName(querySentenceTotalDTO.getBookName())));
    }

    @PostMapping
    public Result save(@RequestBody EntryDTO entryDto) {
        log.info("新增录入信息：{}", entryDto);
        if(StringUtils.isEmpty(entryDto.getSentence()) && StringUtils.isEmpty(entryDto.getSentence2())
                && StringUtils.isEmpty(entryDto.getDzSentence()) && (entryDto.getManwengLd()==null||StringUtils.isEmpty(entryDto.getDzSentence()) )){
            throw new BaseException("没有任何录入信息，保存失败！！！" +
                    "（之前保存会插入空数据，但是对业务影响不大···）");
        }
        entryService.save(entryDto);
        return Result.success();
    }

    @PostMapping("/content")
    public Result<Entry> selectEntryBook(@RequestBody Entry entry) {
        log.info("查询录入内容：{}", entry);
        return Result.success(entryService.selectEntryBook(entry));
    }

    @GetMapping("/jdbPicForChapter")
    @Cacheable(value = "jdbCPicForChapterCache", key = "'JdbContentForChapter-' + #jdbContentForChapterDTO.bookId + #jdbContentForChapterDTO.bookName + #jdbContentForChapterDTO.index")
    public Result<List<PictureVO>> jdbCPicForChapter(JdbContentForChapterDTO jdbContentForChapterDTO) {
        log.info("查询当前章节的所有经典版图片：{}", jdbContentForChapterDTO);
        CatalogQueryDTO catalogQueryDTO = new CatalogQueryDTO();
        BeanUtils.copyProperties(jdbContentForChapterDTO, catalogQueryDTO);
        CatalogBook catalogBook = commonService.getMinorityCatalogBookByBookAndIndex(catalogQueryDTO);
        List<Picture> pictureList = pictureMapper.selectAllPictureByid(catalogBook.getId());
        return Result.success(pictureList.stream()
                .map(picture -> new PictureVO(
                        picture.getId(),
                        picture.getPictureUrl(),
                        picture.getOrder()))
                .collect(Collectors.toList()));
    }
}
